package com.goodfox.web.generic.attribute.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.goodfox.web.generic.account.entity.Account;
import com.goodfox.web.generic.attribute.entity.AtrType;
import com.goodfox.web.generic.attribute.entity.Attribute;
import com.goodfox.web.generic.attribute.service.AttributeService;
import com.goodfox.web.generic.authority.service.PowerService;
import com.goodfox.web.generic.provide.entity.Pager;
import com.goodfox.web.generic.provide.exception.EntityValidateException;
import com.goodfox.web.generic.provide.service.EntityService;
import com.goodfox.web.generic.provide.util.ParameterUtil;

/**
 * 属性管理Action类,封装所有与属性相关的action请求链接
 * 
 * @author qin gt
 * 
 */
@Controller
@RequestMapping("/attribute")
public class AttributeController {

	/** log4j日志器 */
	private Logger logger = Logger.getLogger(AttributeController.class);

	/** 属性Service */
	@Autowired
	private AttributeService attributeService;
	
	/** 权限Service */
	@Autowired
	private PowerService powerService;
	
	/** 实体Service */
	@Autowired
	private EntityService entityService;
	
	/**
	 * 进入属性管理首页
	 * @return 属性管理首页
	 */
	@RequestMapping(value = "goAttributeIndex.shtml")
	public String goAttributeIndex(HttpServletRequest request, ModelMap model) {
		logger.info("进入属性管理首页");
		//判断是否有权限
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			List<AtrType> typeList = attributeService.queryAtrTypeList();
			model.put("typeList", typeList);

			int currentPage=1;
			if(!ParameterUtil.getReqParaValue(request,"pageNum").equals("")){
				currentPage=Integer.parseInt(ParameterUtil.getReqParaValue(request,"pageNum"));
			}
			int numPerPage=15;
			if(!ParameterUtil.getReqParaValue(request,"numPerPage").equals("")){
				numPerPage=Integer.parseInt(ParameterUtil.getReqParaValue(request,"numPerPage"));
			}
			
		    Map queryMap=entityService.fillQueryMap(request,model);
			Pager<AtrType> pager=attributeService.queryAtrTypePager(currentPage, numPerPage, queryMap);

		    model.put("atrTypeList", pager.getEntityList());
			
			model.put("totalCount", pager.getAllCount());
			model.put("currentPage", currentPage);
			model.put("numPerPage", numPerPage);
			return "attribute/attributeIndex";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}

	/**
	 * 执行属性(类型)查询
	 * @param request
	 * @return
	 */
	@RequestMapping(value="attrQuery.shtml")
	@ResponseBody
	public Map atrQuery(HttpServletRequest request){
		//返回对象
		Map rspMap=new HashMap();
		//渲染器
		String sEcho = request.getParameter("sEcho"); 
		//起始记录数
	    int start = Integer.parseInt(request.getParameter("iDisplayStart"));  
	    //每页记录数
	    int count = Integer.parseInt(request.getParameter("iDisplayLength")); 
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			logger.info("执行属性查询");
		    //查询条件对象
		    HashMap queryMap=new HashMap();
			queryMap.put("typeValue", ParameterUtil.getReqParaValue(request,"typeValue"));
			
			//查询数据
			Pager<AtrType> pager=attributeService.queryAtrTypePager(start, count, queryMap);
			String[][] data=new String[pager.getEntityList().size()][];
			for(int i=0;i<pager.getEntityList().size();i++){
		    	AtrType attrType=pager.getEntityList().get(i);
				data[i]=new String[]{
						"",
						attrType.getTypeName(),
						attrType.getAtrNames(),
						attrType.getTypeValue()+"~_~"+attrType.getTypeName()
						};
			}
			
			//当记录数
			rspMap.put("iTotalRecords", pager.getEntityList().size());
			//总记录数
			rspMap.put("iTotalDisplayRecords",pager.getAllCount());
			rspMap.put("sEcho", sEcho);
			rspMap.put("aaData", data);
			rspMap.put("iPower", true);
		}else{
			//当记录数
			rspMap.put("iTotalRecords", 0);
			//总记录数
			rspMap.put("iTotalDisplayRecords",0);
			rspMap.put("sEcho", sEcho);
			rspMap.put("aaData", new String[0][]);
			rspMap.put("iPower", false);
		}
		return rspMap;
	}

	/**
	 * 跳转到属性添加页面
	 * @param request
	 * @param model
	 * @return 属性添加页面
	 */
	@RequestMapping(value = "goAttributeAdd.shtml")
	public String goAttributeAdd(HttpServletRequest request, ModelMap model) {
		logger.info("进入属性新增页");
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			AtrType atrType = attributeService.getAtrTypeByValue(ParameterUtil.getReqParaValue(request, "typeValue"));
			model.addAttribute("attrType", atrType);
			return "attribute/attributeAdd";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}

	/**
	 * 添加属性信息
	 * @param reqMap
	 * @return
	 */
	@RequestMapping(value ="attributeAdd.shtml")
	@ResponseBody
	public Map attributeAdd(HttpServletRequest request) {
		logger.info("执行属性新增");
		Map rspMap = new HashMap();
		rspMap.put("navTabId", "attributeHome");
		rspMap.put("rel", "");
		rspMap.put("callbackType", "closeCurrent");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try {
				Attribute entity=(Attribute)entityService.fillEntity(request,Attribute.class);
				attributeService.addAttribute(entity,request.getSession().getAttribute("loginLogId").toString());
				statusCode="200";
				message="新增成功！";
			}catch(EntityValidateException evex){
				message="新增失败:"+evex.getMessage()+"！";
			}catch(Exception ex){
				logger.error("attributeAdd:", ex);
				message="新增失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("attributeAdd rspMap:"+rspMap);
		return rspMap;
	}

	/**
	 * 准备修改属性信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "goAttributeModify.shtml")
	public String goAttributeModify(HttpServletRequest request, ModelMap model) {
		logger.info("进入属性更新页");
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			// 查询属性类型
			AtrType attrType = attributeService.getAtrTypeByValue(ParameterUtil.getReqParaValue(request, "typeValue"));
			// 查询属性内容
			List<Attribute> attributeList = attributeService.queryAttributeListByTypeId(attrType.getTypeValue());
			model.put("attrType", attrType);
			model.put("attributeList", attributeList);
			return "attribute/attributeModify";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}

	/**
	 * 修改属性信息
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "attributeModify.shtml")
	@ResponseBody
	public Map attributeModify(HttpServletRequest request) {
		logger.info("执行属性更新");
		Map rspMap = new HashMap();
		rspMap.put("navTabId", "");
		rspMap.put("rel", "attributeHome");
		rspMap.put("callbackType", "update");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				AtrType newEny=(AtrType)entityService.fillEntity(request,AtrType.class);
				AtrType oldEny=attributeService.getAtrTypeByValue(newEny.getTypeValue());
				attributeService.modifyAttribute(oldEny,newEny,request.getSession().getAttribute("loginLogId").toString());
				statusCode="200";
				message="更新成功！";
			}catch(EntityValidateException evex){
				message="更新失败:"+evex.getMessage()+"！";
			}catch(Exception e){
				logger.error("attributeModify异常：", e);
				message="更新失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("attributeModify rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 查询属性详细信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "goAttributeDetail.shtml")
	public String goAttributeDetail(HttpServletRequest request, ModelMap model) {
		logger.info("进入属性信息页面");
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			// 查询属性类型
			AtrType atrType = attributeService.getAtrTypeByValue(ParameterUtil.getReqParaValue(request, "typeValue"));
			// 查询属性内容
			List<Attribute> attributeList = attributeService.queryAttributeListByTypeId(atrType.getTypeValue());
			model.put("attrType", atrType);
			model.put("attributeList", attributeList);
			return "attribute/attributeDetail";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}

}
